package org.codingeasy.oauth.client.utils;

import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 本地存储  
* @author : KangNing Hu
*/
public class LocalStore {

	public static  Type storeType = Type.SESSION;

	public static void setStoreType(Type type){
		storeType = type;
	}


	/**
	 * 获取本地仓储的属性值
	 * @param request 请求对象
	 * @param name 属性名称
	 * @return 返回属性值
	 */
	public  static String get(HttpServletRequest request , String name){
		if (StringUtils.isEmpty(name)){
			return null;
		}
		switch (storeType){
			case COOKIE:
				Cookie cookie = getCookie(request, name);
				return cookie == null ? null : cookie.getValue();
			case REQUEST:
				return request.getParameter(name);
			case SESSION:
				return (String) request.getSession().getAttribute(name);

		}
		return null;
	}


	/**
	 * 设置属性值到本地仓储
	 * @param request 请求对象
	 * @param name 属性名称
	 */
	public static void add(HttpServletRequest request , HttpServletResponse response, String name , String value){
		if (StringUtils.isEmpty(name)){
			return;
		}
		switch (storeType){
			case COOKIE:
				response.addCookie(new Cookie(name , value));
				break;
			case SESSION:
				request.getSession().setAttribute(name , value);
				break;
		}
	}


	/**
	 * 将属性移除本地仓储
	 * @param request 请求对象
	 * @param name 属性名称
	 */
	public static void remove(HttpServletRequest request , String name){
		switch (storeType){
			case COOKIE:
				Cookie cookie = getCookie(request, name);
				if (cookie != null) {
					cookie.setValue(null);
				}
			case SESSION:
				request.getSession().removeAttribute(name);
		}
	}


	/**
	 * 获取cookie
	 * @param request 请求对象
	 * @param name cookie 名称
	 * @return 返回名称对应的cookie对象 如果不存在则返回null
	 */
	public static Cookie getCookie(@NotNull HttpServletRequest request , String name){
		if (StringUtils.isEmpty(name)){
			return null;
		}
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies){
			if (name.equals(cookie.getName())){
				return cookie;
			}
		}
		return null;
	}

	/**
	 * 存储类型
	 * @author hukangning
	 */
	public  enum Type{
		SESSION,
		REQUEST,
		COOKIE
	}
}
